<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\model;

use app\api\service\Token;
use app\lib\exception\CurdException;
use think\Config;
use think\Db;

/**
 * 用户微信表
 * Class UserWeixin
 * @package app\api\model
 */
class UserWeixin extends BaseModel
{
    /**
     * @Desc 获取用户手机号
     *
     * @param $value
     * @param $data
     *
     * @return bool|float|mixed|string|null
     */
    protected function getSexAttr($value, $data)
    {
        $sex = '';
        switch ($data['gender']) {
            case 1:
                $sex = '男';
                break;
            case 2:
                $sex = '女';
                break;
            case 0:
                $sex = '保密';
                break;
        }
        return $sex;
    }

    /**
     * @Desc 根据省市ID获取地址
     *
     * @param $value
     * @param $data
     *
     * @return string
     */
    protected function getAddressAttr($value, $data)
    {
        $address = '';
        if ($data['province_id'] && $data['city_id']) {
            $ids = [$data['province_id'], $data['city_id']];
            $area = Db::name('china')->whereIn('id', $ids)->column('name');
            [$province, $city] = $area;
            $address = "{$province} / {$city}";
        }
        return $address;
    }

    /**
     * @Desc 通过openid获取用户对象
     *
     * @param string $openid
     *
     * @return UserWeixin|null 用户对象
     */
    public static function getUserByOpenid($openid)
    {
        return self::get(['open_id' => $openid]);
    }

    /**
     * @Desc 获取用户对象
     * @return array
     */
    public static function getUser()
    {
        $uid = Token::getUidFromCache();
        $field = 'id, avatar_url, nick_name, true_name, mobile, email, gender, birthday, province_id, city_id, member';
        $user = (new self)->field($field)->where('id', '=', $uid)->find();
        return $user->append(['sex', 'address'])->toArray();
    }

    /**
     * @Desc 新增用户对象
     *
     * @param array $wxResult
     *
     * @return string|false 用户id
     */
    public static function insertUserByOpenid(array $wxResult)
    {
        //INSERT INTO `cd_user_weixin` SET `appid` = ?, `open_id` = ?, `session_key` = ?, `session_id` = ?, `create_time` = ?, `update_time` = ?
        $time = time();
        $data = [
            'appid'       => Config::get('wechat.appid'),
            'open_id'     => $wxResult['openid'],
            'session_key' => $wxResult['session_key'],
            'session_id'  => sha1(uniqid()),
            'create_time' => $time,
            'update_time' => $time,
        ];
        $user = self::create($data);
        $usersData = [
            'open_id'        => $wxResult['openid'],
            'user_weixin_id' => $user->id,
            'create_time'    => $time,
            'update_time'    => $time,
        ];
        $users = Users::get(['open_id' => $wxResult['openid']]);
        if (null == $users) {
            Users::create($usersData);
        }
        return $user->getData('id');
    }

    /**
     * @Desc 更新用户数据
     *
     * @param mixed $userInfo
     *
     * @return array
     */
    public static function updateUser($userInfo)
    {
        $id = Token::getUidFromCache();
        $field = ['avatar_url', 'nick_name', 'true_name', 'email', 'mobile', 'gender', 'birthday', 'province_id', 'city_id'];
        $user = self::update($userInfo, ['id' => $id], $field);
        if (!$user) {
            throw new CurdException([
                'message'   => '信息更新失败',
                'errorCode' => 60002,
            ]);
        }
        return self::getUser();
    }

    /**
     * @Desc 查询用户积分
     * @return bool|float|mixed|string|null
     */
    public static function getMemberData()
    {
        $id = Token::getUidFromCache();
        $member = (new self)->where('id', $id)->value('member');
        return ['member' => $member];
    }

    /**
     * @Desc 更新用户手机号
     *
     * @param $mobile
     *
     * @return array
     */
    public static function updateUserMobile($mobile)
    {
        $id = Token::getUidFromCache();
        self::update(['mobile' => $mobile], ['id' => $id]);
        return self::getUser();
    }
}